package ar.com.ford.it.fullEconomics.view.action;

import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.facade.CommodityFacade;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp02Commodity;
import ar.com.ford.it.fullEconomics.view.form.CommodityForm;
import ar.com.ford.it.fullEconomics.wslx.FullEconomicsWslxUser;
import ar.com.ford.it.webengine.facade.FacadeProvider;
import ar.com.ford.it.webengine.struts.AbstractBaseAction;
import ar.com.ford.it.webengine.struts.FordActionMapping;
import ar.com.ford.it.webengine.websession.WebSession;

public class CommodityAction extends AbstractBaseAction {

    /**
     * Setea el mensaje de "busqueda sin resultados" cuando la busqueda no trae
     * resultados
     * 
     * @param request
     * Request donde se guarda el mensaje
     */
    private void searchWithNoResults(HttpServletRequest request) {
        ActionMessages am = new ActionMessages();
        MessageResources messageResources = (MessageResources) getResources(request);

        am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                "customMessage", messageResources
                        .getMessage("message.noResults")));
        saveMessages(request, am);
    }

    /**
     * Resetea el formulario y envia a la pagina inicial de Commoditys
     * 
     */
    public ActionForward initPage(FordActionMapping mapping,
                                  ActionForm actionForm,
                                  HttpServletRequest request,
                                  HttpServletResponse response,
                                  WebSession webSession, ActionMessages msgs,
                                  ActionMessages warns, ActionMessages errorMsgs) {
        CommodityForm form = (CommodityForm) actionForm;

        form.resetForm();
        return mapping.findForward("success");
    }

    /**
     * Resetea los campos para el create/update
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward clearCreateFields(FordActionMapping mapping,
                                           ActionForm actionForm,
                                           HttpServletRequest request,
                                           HttpServletResponse response,
                                           WebSession webSession,
                                           ActionMessages msgs,
                                           ActionMessages warns,
                                           ActionMessages errorMsgs) {
        CommodityForm form = (CommodityForm) actionForm;

        form.clearCreateUpdateFields();
        return mapping.findForward("success");
    }

    /**
     * Se encarga del manejo de la busqueda de Commodities
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward findCommodities(FordActionMapping mapping,
                                         ActionForm actionForm,
                                         HttpServletRequest request,
                                         HttpServletResponse response,
                                         WebSession webSession,
                                         ActionMessages msgs,
                                         ActionMessages warns,
                                         ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();

        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        CommodityForm form = (CommodityForm) actionForm;
        CommodityFacade facade = (CommodityFacade) FacadeProvider.getFacade(
                request, CommodityFacade.class);
        Collection<Teesp02Commodity> res = null;
        try {
            String code = form.getCodeFind();
            String name = form.getNameFind();
            res = facade.findCommodities(code, name, user.getTeesg01Plant());
            if (res.isEmpty()) {
                searchWithNoResults(request);
            }
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        form.setCommoditys(res);
        form.clearCreateUpdateFields();
        return mapping.findForward("success");
    }

    /**
     * Se encarga del manejo de la busqueda de Commodities
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward findCommoditiesByParts(FordActionMapping mapping,
                                                ActionForm actionForm,
                                                HttpServletRequest request,
                                                HttpServletResponse response,
                                                WebSession webSession,
                                                ActionMessages msgs,
                                                ActionMessages warns,
                                                ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();

        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        CommodityForm form = (CommodityForm) actionForm;
        CommodityFacade facade = (CommodityFacade) FacadeProvider.getFacade(
                request, CommodityFacade.class);
        Collection<Teesp02Commodity> res = null;
        try {
            String prefix = form.getPrefix();
            String base = form.getBase();
            String suffix = form.getSuffix();
            /*
             * if (StringUtils.isBlank(code) && StringUtils.isBlank(name)) {
             * searchWithNoResults(request); } else {
             */
            res = facade.findCommoditiesByParts(prefix, base, suffix, user
                    .getTeesg01Plant());
            if (res.isEmpty()) {
                searchWithNoResults(request);
            }
            // }
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        form.setCommoditys(res);
        form.clearCreateUpdateFields();
        return mapping.findForward("success");
    }

    /**
     * Setea los campos de edicion de Commoditys con los valores del Commodity
     * seleccionado mediante el listado
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward editCommodity(FordActionMapping mapping,
                                       ActionForm actionForm,
                                       HttpServletRequest request,
                                       HttpServletResponse response,
                                       WebSession webSession,
                                       ActionMessages msgs,
                                       ActionMessages warns,
                                       ActionMessages errorMsgs) {
        CommodityForm form = (CommodityForm) actionForm;

        form.setCommodityForEdit(form.getCommoditySelected());
        return mapping.findForward("success");
    }

    /**
     * En caso de que se haya seleccionado algun Commodity del listado, entonces
     * lo actualiza, sino llama al metodo encargado de crear el Commodity
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward createUpdateCommodity(FordActionMapping mapping,
                                               ActionForm actionForm,
                                               HttpServletRequest request,
                                               HttpServletResponse response,
                                               WebSession webSession,
                                               ActionMessages msgs,
                                               ActionMessages warns,
                                               ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();

        CommodityForm form = (CommodityForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        CommodityFacade facade = (CommodityFacade) FacadeProvider.getFacade(
                request, CommodityFacade.class);
        Teesp02Commodity commodity = null;

        try {
            // Si la moneda existe por codigo
            commodity = facade.findCommodityByName(form.getName(), user
                    .getTeesg01Plant());
            if (form.getCode() == null) {
                if (commodity == null) {
                    facade.createCommodity(form.getCommodityForCreate(), user);
                } else {
                    am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                            "commodity.error.existingName", commodity
                                    .getEesp02CommodityNumberK().toString()));
                    saveErrors(request, am);
                }

            } else {
                if (commodity == null
                        || commodity.getEesp02CommodityNumberK() == form
                                .getCommoditySelected()
                                .getEesp02CommodityNumberK()) {
                    facade.updateCommodity(form.getCommodityForUpdate(form
                            .getCommoditySelected()), user);
                } else {
                    am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                            "commodity.error.existingName", commodity
                                    .getEesp02CommodityNumberK().toString()));
                    saveErrors(request, am);
                }
            }
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }

    /**
     * Elimina el Commodity seleccionado, verificando que no tenga elementos
     * relacionados
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward deleteCommodity(FordActionMapping mapping,
                                         ActionForm actionForm,
                                         HttpServletRequest request,
                                         HttpServletResponse response,
                                         WebSession webSession,
                                         ActionMessages msgs,
                                         ActionMessages warns,
                                         ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();

        CommodityForm form = (CommodityForm) actionForm;
        CommodityFacade facade = (CommodityFacade) FacadeProvider.getFacade(
                request, CommodityFacade.class);
        String[] commRelatedElementsIDs;
        Teesp02Commodity commodity = form.getCommoditySelected();

        try {
            // busco los elementos relacionados al commodity
            commRelatedElementsIDs = facade
                    .commoditysRelatedElements(commodity);
            // si no encuentro nada, borro el commodity
            if (commRelatedElementsIDs[0] == null
                    && commRelatedElementsIDs[1] == null
                    && commRelatedElementsIDs[2] == null
                    && commRelatedElementsIDs[3] == null
                    && commRelatedElementsIDs[4] == null) {
                facade.deleteCommodity(form.getCommoditySelected());
            } else {
                // si se encontro algun elemento relacionado, muestro un mensaje
                // con los IDs de los elementos encontrados
                am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                        "commodity.error.relatedElementsPending"));

                if (commRelatedElementsIDs[0] != null) {
                    am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                            "commodity.error.relatedCostStructPending",
                            commRelatedElementsIDs[0]));
                }
                if (commRelatedElementsIDs[1] != null) {
                    am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                            "commodity.error.relatePayPolicyPending",
                            commRelatedElementsIDs[1]));
                }
                if (commRelatedElementsIDs[2] != null) {
                    am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                            "commodity.error.relatedRequestPending",
                            commRelatedElementsIDs[2]));
                }
                if (commRelatedElementsIDs[3] != null) {
                    am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                            "commodity.error.relatedPartPending",
                            commRelatedElementsIDs[3]));
                }
                if (commRelatedElementsIDs[4] != null) {
                    am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                            "commodity.error.relatedAgreementPending",
                            commRelatedElementsIDs[4]));
                }
                /*am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                        "commodity.error.closeUl"));*/
                saveErrors(request, am);
            }
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }
    
    /**
     * Setea los campos de edicion de Commoditys con los valores del Commodity
     * seleccionado mediante el listado
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward commodityMembers(FordActionMapping mapping,
                                       ActionForm actionForm,
                                       HttpServletRequest request,
                                       HttpServletResponse response,
                                       WebSession webSession,
                                       ActionMessages msgs,
                                       ActionMessages warns,
                                       ActionMessages errorMsgs) {
        CommodityForm form = (CommodityForm) actionForm;
        
        request.setAttribute("commodity", form.getCommoditySelected());

        return mapping.findForward("success");
    }
}
